//
//  ComplaintFeedbackViewController.m
//  PigMarket
//
//  Created by mac on 2019/3/23.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "ComplaintFeedbackViewController.h"
#import "MeatComplaintCustomCell.h"
#import "MeatComplaintIphoneCell.h"

#import "MeatComplaintModel.h"

@interface ComplaintFeedbackViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) UIView *tipView; //提示
@property (nonatomic, strong) UIView *footer;
@property (strong, nonatomic) UIImagePickerController *imagePicker;
@property (nonatomic, strong) UITapGestureRecognizer *tap;
@property (nonatomic, strong) MeatComplaintModel *model;
@property (nonatomic, strong) ComplaintFeedbackList *questionModel;

/**
 photosArr
 */
@property (nonatomic , strong) NSMutableArray *photosArr;


@property (nonatomic, strong) NSMutableArray *selectedIds;


@end

@implementation ComplaintFeedbackViewController


#pragma mark - view life cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpView];
}

#pragma mark - init method

- (void)setUpView {
    [self initView];
    [self initData];
    [self addNotifications];
}

- (void)initView {
    
    self.baseNavView.navTitleLabel.text = @"意见反馈";
    
    self.view.backgroundColor = mBackgroudColor;
    CGFloat kTableViewHeight = KScreenHeight - TJ_NavBarHeight;
    self.tableView.height = kTableViewHeight;
    self.tableView.mj_y = self.baseNavView.bottom;
}

- (void)initData {
    
    [self getAllQuestionItemRequest];
}

#pragma mark - private method

//获取反馈的问题列表
- (void)getAllQuestionItemRequest {
    
    @weakify(self);
    [[[PigMarketApi sharedInstance] getCompaintFeedbackList] subscribeNext:^(ComplaintFeedbackList * _Nullable complaintFeedbackList) {
        @strongify(self);
        self.questionModel = complaintFeedbackList;
        [self.tableView reloadData];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
    }];
}

//上传图片
- (void)uploadPhotoRequestWithPhotosArr:(NSArray *)photosArr {
    
    NSString *phone = self.questionModel.phone;
    NSString *description = self.model.content;
    
    NSString *questionsId = [self getAllQuestionId];
    if ([questionsId isBlankString]) {
        [self toastWithContent:@"请选择您想反馈的问题"];
        return;
    }

    if ([description isBlankString]) {
        [self toastWithContent:@"请输入问题描述"];
        return;
    }
    
    if (![phone isValidPhoneNumber]) {
        [self toastWithContent:@"请输入手机号码"];
        return;
    }
    
    
    [self showProgressView];
    NSString *account = [UserInfoDataProvider sharedInstance].userInfo.phone;
    @weakify(self);
    [[[PigMarketApi sharedInstance] uploadPhotosWithPhotosArr:[photosArr copy] account:account type:UpDateImageType_Other] subscribeNext:^(PhotosList * _Nullable photoList) {
        @strongify(self);
        
        [self.photosArr addObjectsFromArray:photoList.imgList];
        [self saveRequestByQuestionId:questionsId phone:phone questionTest:description];
        
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self hideProgressView];
        [self handlingError:error];
    }];
}



- (void)saveRequestByQuestionId:(NSString *)questionId phone:(NSString *)phone questionTest:(NSString *)questionTest {
    
    NSNumber *memberId = [UserInfoDataProvider sharedInstance].userInfo.memberId;
    
    NSMutableArray *photosNameArr = [[NSMutableArray alloc] init];
    for (Photos *model in self.photosArr) {
        [photosNameArr addObject:model.imgName];
    }
    
    ComplaintFeedbackParam *param = [[ComplaintFeedbackParam alloc] init];
    param.memberId = memberId;
    param.opinionTypeId = questionId;
    param.oDescribe = questionTest;
    param.phone = phone;
    if (photosNameArr.count > 0) {//判断时候添加了图片
        param.imgs = photosNameArr;
    }
    @weakify(self);
    [[[PigMarketApi sharedInstance] commitComplaintFeedbackWith:param] subscribeNext:^(NSNull * _Nullable x) {
        @strongify(self);
        [self hideProgressView];
        [self toastWithContent:@"提交成功"];
        [self.navigationController popViewControllerAnimated:YES];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self hideProgressView];
        [self handlingError:error];
    }];
}

- (NSString *)getAllQuestionId {
    
    __block NSMutableArray *aimArray = [NSMutableArray array];
    [self.questionModel.list enumerateObjectsUsingBlock:^(ComplaintFeedback * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if (obj.isSelected) {
            [aimArray addObject:obj.dataDictId];
        }
    }];
    
    return [aimArray componentsJoinedByString:@"-"];
}


#pragma mark - tableview delegate/dataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section == 0) {
        return self.questionModel.list.count;
    }
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 52;
    }else if (indexPath.section == 1){
        return 34;
    }else if (indexPath.section ==2){
        return 251;
    }else if (indexPath.section == 3){
        return 10;
    }
    return 54;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        ComplaintFeedback *item = self.questionModel.list[indexPath.row];
        cell.textLabel.text = item.dataKey;
        cell.textLabel.textColor = UIColorFromRGB(0x363636);
        cell.textLabel.font = mFont(16);
        cell.imageView.image = item.isSelected ?[UIImage imageNamed:@"meat_complaints_selected"]
                                               :[UIImage imageNamed:@"meat_complaints_unselected"];

        return cell;
        
    }else if (indexPath.section == 1){
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell_section" forIndexPath:indexPath];
        cell.textLabel.text = @"请输入您的问题或照片";
        cell.textLabel.textColor = UIColorFromRGB(0x969696);
        cell.textLabel.font = mFont(14);
        cell.backgroundColor = mBackgroudColor;
        return cell;
    }else if (indexPath.section == 2){
        
        MeatComplaintCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ComplaintBusinessCustomCell"];
        cell.placeHolderLab.text = @"请输入您的问题...";
        cell.model = self.model;
        
        kWeakSelf(self);
        cell.dealPhotoBlock = ^(NSInteger index, DealPhotoOperation operation) {
            
            if (operation == DealPhotoOperation_Add) {
                [weakself addPhotoOperationByTableView:tableView];
            }else{
                [weakself.model.photos removeObjectAtIndex:index];
                [weakself localReloadTableViewBySection:2];
            }
        };
        
        return cell;
        
    }else if(indexPath.section == 3){
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell_sectionLittle" forIndexPath:indexPath];
        cell.backgroundColor = mBackgroudColor;
        return cell;
    }
    
    MeatComplaintIphoneCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ComplaintBusinessIphoneCell"];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        
        ComplaintFeedback *item = self.questionModel.list[indexPath.row];
        item.isSelected = item.isSelected ?NO :YES;
        [self localReloadTableViewBySection:0];
        //[self checkUpdateDataIsWhole];
    }
}


#pragma mark - UIImagePicker Delegate

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *image = info[UIImagePickerControllerEditedImage];
    if (!image) {
        NSLog(@"获取头像照片失败");
    }else {
        [self.model.photos addObject:image];
        [self localReloadTableViewBySection:2];
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - target action

- (void)submitQuestion{
    
    //[self saveRequest];
    [self uploadPhotoRequestWithPhotosArr:self.model.photos];
}


//跳转相册
- (void)addPhotoOperationByTableView:(UITableView *)tableView{
    //修改头像
    [tableView endEditing:YES];
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    kWeakSelf(self)
    UIAlertAction * cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakself presentViewController:weakself.imagePicker animated:YES completion:nil];
    }];
    UIAlertAction * photosAction = [UIAlertAction actionWithTitle:@"从相册中选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.allowsEditing = YES;
        [weakself presentViewController:picker animated:YES completion:nil];
    }];
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:cameraAction];
    [alert addAction:photosAction];
    [alert addAction:cancelAction];
    [weakself presentViewController:alert animated:YES completion:nil];
}


#pragma mark - setter and getter

- (void)registerTableViewCell{
    
    self.tableView.separatorColor = UIColorFromRGB(0xF2F2F2);
    self.tableView.tableHeaderView = self.tipView;
    self.tableView.tableFooterView = self.footer;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell_section"];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell_sectionLittle"];
    [self.tableView registerClass:[MeatComplaintCustomCell class] forCellReuseIdentifier:@"ComplaintBusinessCustomCell"];
    [self.tableView registerClass:[MeatComplaintIphoneCell class] forCellReuseIdentifier:@"ComplaintBusinessIphoneCell"];
}


- (UIView *)tipView{
    if (!_tipView) {
        _tipView = [[UIView alloc] init];
        _tipView.frame = CGRectMake(0, 0, KScreenWidth, 34);
        _tipView.backgroundColor = mBackgroudColor;
        
        UILabel *label = [UILabel makeLabelWithText:@"请选择您想反馈的问题（可多选）" textColor:UIColorFromRGB(0x969696) font:mFont(14) textAliment:0];
        label.frame = CGRectMake(15, 0, KScreenWidth - 15, 34);
        [_tipView addSubview:label];
        
    }
    return _tipView;
}

- (UIView *)footer{
    if (!_footer) {
        _footer = [[UIView alloc] init];
        _footer.backgroundColor = mBackgroudColor;
        _footer.frame = CGRectMake(0, 0, KScreenWidth, 148);
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:@"确定" forState:UIControlStateNormal];
        [button setTitleColor:KWhiteColor forState:UIControlStateNormal];
        button.titleLabel.font = mMediumFont(16);
        UIImageView *bg = [[UIImageView alloc] init];
        bg.image = [UIImage imageNamed:@"meat_me_submit"];
        bg.frame = CGRectMake(0, 0, KScreenWidth - 30, 48);
        [button insertSubview:bg atIndex:0];
        button.frame = CGRectMake(20, 50, KScreenWidth -40, 48);
        [self addShadowAndCircleCorner:button.layer corner:5];
        [button addTarget:self action:@selector(submitQuestion) forControlEvents:UIControlEventTouchUpInside];
        [_footer addSubview:button];
    }
    return _footer;
}

- (UIImagePickerController *)imagePicker
{
    if (!_imagePicker) {
        _imagePicker = [[UIImagePickerController alloc]init];
        _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        _imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
        _imagePicker.allowsEditing = YES;
        _imagePicker.delegate = self;
    }
    return _imagePicker;
}

- (MeatComplaintModel *)model{
    if (!_model) {
        _model = [[MeatComplaintModel alloc] init];
    }
    return _model;
}

- (NSMutableArray *)selectedIds{
    
    if (!_selectedIds) {
        _selectedIds = [NSMutableArray array];
    }
    return _selectedIds;
}

#pragma mark - other methods

- (void)textViewDidChanged:(NSNotification *)notification
{
    UITextView *textView = notification.object;
    self.model.content = textView.text;
}

- (void)textFieldDidChanged:(NSNotification *)notification
{
    UITextField *textField = notification.object;
    self.questionModel.phone = textField.text;
}

- (void)keyboardDidShow:(NSNotification *)notification{
    NSDictionary *info = [notification userInfo];
    CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    kWeakSelf(self);
    [UIView animateWithDuration:duration animations:^{
        weakself.tableView.mj_y = 0;
    }];
    
    //当键盘升起的时候添加点击降落操作
    if (!self.tap) {
        self.tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
    }
    [self.view addGestureRecognizer:self.tap];
}

//取消键盘响应
- (void)hideKeyboard{
    
    [self.view endEditing:YES];
}


- (void)keyboardWillHidden:(NSNotification *)notification{
    
    [UIView animateWithDuration:AnimationTime animations:^{
        self.tableView.mj_y = TJ_NavBarHeight;
    }];
    
    if (self.tap) {
        [self.view removeGestureRecognizer:self.tap];
    }
}

- (void)addNotifications{
    
    [kNotificationCenter addObserver:self selector:@selector(textViewDidChanged:) name:UITextViewTextDidChangeNotification object:nil];
    [kNotificationCenter addObserver:self selector:@selector(textFieldDidChanged:) name:UITextFieldTextDidChangeNotification object:nil];
    [kNotificationCenter addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardWillShowNotification object:nil];
    [kNotificationCenter addObserver:self selector:@selector(keyboardWillHidden:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)removeNotifications{
    
    [kNotificationCenter removeObserver:self name:UITextViewTextDidChangeNotification object:nil];
    [kNotificationCenter removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
    [kNotificationCenter removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [kNotificationCenter removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)dealloc
{
    [self removeNotifications];
}


@end

